package com.shuang.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shuang.common.JsonUtils;
import com.shuang.common.PageObject;
import com.shuang.mapper.DbUserMapper;
import com.shuang.pojo.DbUser;
import com.shuang.pojo.DbUserExample;
import com.shuang.pojo.DbUserExample.Criteria;
import com.shuang.redis.JedisClient;
import com.shuang.service.DbUserService;

@Service("dbUserService")
public class DbUserServiceImpl implements DbUserService {

	@Value("${REDIS_USER_SESSION_KEY}")
	private String REDIS_USER_SESSION_KEY;
	@Value("${REDIS_SESSION_EXPIRE}")
	private Integer REDIS_SESSION_EXPIRE;
	@Resource(name = "dbUserMapper")
	private DbUserMapper dbUserMapper;
	@Resource(name = "jedisClient")
	private JedisClient jedisClient;

	@Override
	public DbUser getDbUserByUid() {
		return dbUserMapper.selectByPrimaryKey(1L);
	}

	@Override
	public PageObject<DbUser> getAdminList(int page, int rows) {
		return getUserOrAdminList(page, rows, (short) 1);
	}

	@Override
	public PageObject<DbUser> getUserList(int page, int rows) {
		return getUserOrAdminList(page, rows, (short) 0);
	}

	@Override
	public int insertUser(DbUser dbUser) throws Exception {
		if (dbUserMapper.insert(dbUser) > 0) {
			return 200;
		} else {
			throw new Exception();
		}
	}

	@Override
	public int updateUser(DbUser dbUser) throws Exception {
		DbUserExample example = new DbUserExample();
		Criteria criteria = example.createCriteria();
		criteria.andUIdEqualTo(dbUser.getuId());
		int result = dbUserMapper.updateByExampleSelective(dbUser, example);
		if (result > 0) {
			return 200;
		} else {
			throw new Exception();
		}
	}

	@Override
	public int updateUserStatusById(List<Long> uIds, short status)
			throws Exception {
		DbUser record = new DbUser();
		record.setuStatus(status);

		DbUserExample example = new DbUserExample();
		Criteria criteria = example.createCriteria();
		criteria.andUIdIn(uIds);
		int result = dbUserMapper.updateByExampleSelective(record, example);
		if (result > 0) {
			return 200;
		} else {
			throw new Exception();
		}

	}

	@Override
	public PageObject<DbUser> getUserListByExample(DbUser dbUser, int page,
			int rows) {
		DbUserExample example = new DbUserExample();
		Criteria criteria = example.createCriteria();
		criteria.andURoleEqualTo((short) 0);
		Long uId = dbUser.getuId();
		if (uId != null && uId != 0) {
			criteria.andUIdEqualTo(uId);
		}
		String uEmail = dbUser.getuEmail();
		if (uEmail != null && uEmail != "") {
			criteria.andUEmailLike("%" + uEmail + "%");
		}
		String uName = dbUser.getuName();
		if (uName != null && uName != "") {
			criteria.andUNameLike("%" + uName + "%");
		}
		// 分页处理
		PageHelper.startPage(page, rows);
		List<DbUser> list = dbUserMapper.selectByExample(example);
		// 获取分页信息对象
		PageInfo<DbUser> pageInfo = new PageInfo<DbUser>(list);
		PageObject<DbUser> pageObject = new PageObject<DbUser>(
				pageInfo.getTotal(), list);
		return pageObject;
	}

	public PageObject<DbUser> getUserOrAdminList(int page, int rows, short role) {
		DbUserExample example = new DbUserExample();
		Criteria criteria = example.createCriteria();
		criteria.andURoleEqualTo(role);
		// 分页处理
		PageHelper.startPage(page, rows);
		List<DbUser> list = dbUserMapper.selectByExample(example);
		// 获取分页信息对象
		PageInfo<DbUser> pageInfo = new PageInfo<DbUser>(list);
		PageObject<DbUser> pageObject = new PageObject<DbUser>(
				pageInfo.getTotal(), list);
		return pageObject;
	}

	@Override
	public Map<String, Object> checkData(String content, String type) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		DbUserExample example = new DbUserExample();
		Criteria criteria = example.createCriteria();
		if (type.equals("1")) {
			criteria.andUNameEqualTo(content);
		} else if (type.equals("2")) {
			criteria.andUEmailEqualTo(content);
		} else if (type.equals("3")) {
			criteria.andUPhoneEqualTo(content);
		} else {
			resultMap.put("status", 403);
			resultMap.put("data", "参数错误");
			return resultMap;
		}
		List<DbUser> result = dbUserMapper.selectByExample(example);
		if (result == null || result.size() == 0) {
			resultMap.put("status", 200);
			resultMap.put("data", "校验数据可用");
			return resultMap;
		} else {
			resultMap.put("status", 403);
			resultMap.put("data", "校验数据不可用");
			return resultMap;
		}
	}

	@Override
	public Map<String, Object> createUser(DbUser dbUser) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		dbUser.setuRegisterTime(new Date());
		// 框架自带md5加密
		dbUser.setuPwd(DigestUtils.md5DigestAsHex(dbUser.getuPwd().getBytes()));
		dbUser.setuRole((short) 0);// 代表前台用户
		dbUser.setuScore(0l);
		dbUser.setuStatus((short) 1);// 可用
		int result = dbUserMapper.insert(dbUser);
		if (result > 0) {
			resultMap.put("status", 200);
		} else {
			resultMap.put("status", 400);
		}
		return resultMap;
	}

	@Override
	public Map<String, Object> userLogin(String uname, String upwd, short role) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		DbUserExample example = new DbUserExample();
		Criteria criteria = example.createCriteria();
		criteria.andURoleEqualTo(role);// 角色登陆
		criteria.andUNameEqualTo(uname);
		criteria.andUPwdEqualTo(DigestUtils.md5DigestAsHex(upwd.getBytes()));
		List<DbUser> list = dbUserMapper.selectByExample(example);
		if (list == null || list.size() == 0) {
			resultMap.put("status", 400);
			resultMap.put("data", "用户名或密码错误");
			return resultMap;
		}
		// 匹配成功，生成token
		String token = UUID.randomUUID().toString();
		// 获取用户信息。清除密码
		DbUser user = list.get(0);
		user.setuPwd(null);
		// 用户信息写入redis
		jedisClient.set(REDIS_USER_SESSION_KEY + ":" + token,
				JsonUtils.objectToJson(user));
		// 设置过期时间
		jedisClient.expire(REDIS_USER_SESSION_KEY + ":" + token,
				REDIS_SESSION_EXPIRE);
		resultMap.put("status", 200);
		resultMap.put("data", "登陆成功");
		resultMap.put("token", token);
		return resultMap;
	}

	@Override
	public Map<String, Object> selectUserFromRedisByToken(String token) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String json = jedisClient.get(REDIS_USER_SESSION_KEY + ":" + token);
		if (json == null || json == "") {
			resultMap.put("status", 400);
			resultMap.put("data", "登陆超时！");
			return resultMap;
		}
		// 更新过期时间
		jedisClient.expire(REDIS_USER_SESSION_KEY + ":" + token,
				REDIS_SESSION_EXPIRE);
		DbUser user = JsonUtils.jsonToPojo(json, DbUser.class);
		resultMap.put("status", 200);
		resultMap.put("data", user);
		return resultMap;
	}

	@Override
	public Map<String, Object> quit(String type, Cookie[] cookies) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (cookies != null && cookies.length > 1) {
			for (Cookie cookie : cookies) {
				if (type.equals("front")) {// 前台退出
					if (cookie.getName().equals("FRONT_SESSION_KEY")) {
						String token = REDIS_USER_SESSION_KEY + ":"
								+ cookie.getValue();
						jedisClient.del(token);
						resultMap.put("status", 200);
						break;
					}
				} else if (type.equals("back")) {
					if (cookie.getName().equals("BACK_SESSION_KEY")) {
						String token = REDIS_USER_SESSION_KEY + ":"
								+ cookie.getValue();
						jedisClient.del(token);
						resultMap.put("status", 200);
						break;
					}
				}
			}
		} else {
			resultMap.put("status", 403);
			resultMap.put("data", "参数错误");
		}
		return resultMap;
	}

	@Override
	public int updateUserSelectiveByPrimaryKey(DbUser dbUserTemp) {
		return dbUserMapper.updateByPrimaryKeySelective(dbUserTemp);
	}
}
